<script setup>
import { ref } from 'vue'
import { updateUserPasswordServer } from '@/api/user.js'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import PageContainer from '@/components/PageContainer.vue'
const formRef = ref(null)
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})
const userStore = useUserStore()
const router = useRouter()

// 自定义校验函数：原密码和新密码不能一样
const validateOldNewPwd = (rule, value, callback) => {
  if (pwdForm.value.old_pwd === pwdForm.value.new_pwd) {
    callback(new Error('原密码和新密码不能一样'))
  } else {
    callback()
  }
}

// 自定义校验函数：新密码与确认密码必须一致
const validateNewRePwd = (rule, value, callback) => {
  if (pwdForm.value.new_pwd !== pwdForm.value.re_pwd) {
    callback(new Error('新密码与确认密码必须一致'))
  } else {
    callback()
  }
}
const rules = {
  old_pwd: [
    { required: true, message: '原密码不能为空', trigger: 'blur' },
    { min: 6, max: 15, message: '原密码必须是6-15位', trigger: 'blur' },
    // 自定义校验：原密码和新密码不能一样
    { validator: validateOldNewPwd, trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 6, max: 15, message: '新密码必须是6-15位', trigger: 'blur' },
    // 自定义校验：原密码和新密码不能一样
    { validator: validateOldNewPwd, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { min: 6, max: 15, message: '确认密码必须是6-15位', trigger: 'blur' },
    // 自定义校验：新密码与确认密码必须一致
    { validator: validateNewRePwd, trigger: 'blur' }
  ]
}

const submit = async () => {
  await formRef.value.validate()
  await updateUserPasswordServer(pwdForm.value)
  ElMessage.success('修改密码成功')
  // 退出登录
  userStore.removeToken()
  userStore.removeUserData()
  userStore.removeUserInfo()
  // 跳转到登录页
  await router.push('/login')
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <page-container title="重置密码">
    <el-form :model="pwdForm" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input type="password" v-model="pwdForm.old_pwd"></el-input>
      </el-form-item>

      <el-form-item label="新密码" prop="new_pwd">
        <el-input type="password" v-model="pwdForm.new_pwd"></el-input>
      </el-form-item>

      <el-form-item label="确认密码" prop="re_pwd">
        <el-input type="password" v-model="pwdForm.re_pwd"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submit">修改密码</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>

<style scoped>
.el-input {
  width: 400px;
}
</style>
